package com.googlecode.afx.view;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.googlecode.afx.i18.exception.ErrorCodeSupportingException;
import com.googlecode.afx.view.validation.ValidationException;

/**
 * Abstract view class that adds error handling in the view, e.g. for displaying an exception.
 * 
 * @author MartinKoster
 *
 */
public abstract class AbstractErrorHandlingView extends AbstractView {

	private static final Log LOG = LogFactory.getLog(AbstractErrorHandlingView.class);
	
	private Throwable throwable;

	public Throwable getThrowable() {
		return throwable;
	}

	public void setThrowable(Throwable throwable) {
		LOG.debug("Setting exception of type '" + throwable.getClass().getName() + "' into view '" + this.getClass().getName()  + "'.");
		this.throwable = throwable;
	}

	/**
	 * Displays the exception in a separate modal dialogue.
	 */
	public void displayThrowable() {
		if(this.throwable instanceof ValidationException) {
			this.getValidationHandler().showValidationErrorDialog((ValidationException) this.throwable);
		} else if(this.throwable instanceof ErrorCodeSupportingException) {
			ErrorCodeSupportingException exc = (ErrorCodeSupportingException) this.throwable;
			String title = this.getMessage("message_error_dialog");
			String  message = this.getMessage(exc.getErrorCode());
			DialogUtils.showErrorDialog(title, message);
		} else {
			LOG.error(this.throwable.getMessage(), this.throwable);
			String title = this.getMessage("message_exception_dialog");
			String message = this.getMessage("message_exception_text");
			DialogUtils.showExceptionDialog(title, message, throwable);
		}
	}
	
	/**
	 * Returns <tt>true</tt> whether there is a <tt>Throwable</tt> associated with this view.
	 * 
	 * @return
	 */
	public boolean hasErrorOccured() {
		return this.throwable != null;
	}
	
	/**
	 * Resets the view and removes the error.
	 */
	public void resetError() {
		this.throwable = null;
	}
}
